package com.lqwu.myoj.judge;

import cn.hutool.json.JSONUtil;
import com.lqwu.myoj.common.ErrorCode;
import com.lqwu.myoj.exception.BusinessException;
import com.lqwu.myoj.exception.ThrowUtils;
import com.lqwu.myoj.judge.codesandbox.CodeSandbox;
import com.lqwu.myoj.judge.codesandbox.CodeSandboxFactory;
import com.lqwu.myoj.judge.codesandbox.CodeSandboxProxy;
import com.lqwu.myoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.lqwu.myoj.judge.codesandbox.model.ExecuteCodeResponse;
import com.lqwu.myoj.judge.strategy.JudgeContext;
import com.lqwu.myoj.model.entity.*;
import com.lqwu.myoj.model.enums.QuestionSubmitStatusEnum;
import com.lqwu.myoj.service.QuestionService;
import com.lqwu.myoj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 评测服务实现
 */
@Service
public class JudgeServiceImpl implements JudgeService{

    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionSubmitService questionSubmitService;
    @Value("${codesandbox.type}")
    private String type;
    @Resource
    private JudgeManager judgeManager;

    /**
     * 根据题目提交id判题
     * @param questionSubmitId
     * @return
     */
    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        // 1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等）
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        ThrowUtils.throwIf(questionSubmit == null, ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        Integer status = questionSubmit.getStatus();
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        // 2）如果题目提交状态不为等待中，就不用重复执行了
        QuestionSubmitStatusEnum statusEnum = QuestionSubmitStatusEnum.getEnumByValue(status);
        if (statusEnum != QuestionSubmitStatusEnum.WAITING){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在执行中");
        }
        // 3）更改判题（题目提交）的状态为 “判题中”，防止重复执行
        QuestionSubmit updateQuestionSubmit = new QuestionSubmit();
        updateQuestionSubmit.setId(questionSubmitId);
        updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(updateQuestionSubmit);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "题目提交更新错误");
        // 4）调用沙箱，获取到执行结果
        CodeSandbox codeSandbox = CodeSandboxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        // 获取输入用例
        List<JudgeCase> judgeCaseList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        // 构建执行代码请求
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .language(language)
                .input(inputList)
                .code(code)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest);
        // 根据结果获取输出列表
        List<String> outputList = executeCodeResponse.getOutputList();
        // 5）根据沙箱的执行结果，设置题目的判题状态和信息
        // 构建上下文信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        // 策略模式,获取默认策略
//        JudgeStrategy judgeStrategy = new DefaultJudgeStrategy();
//        JudgeInfo judgeInfo = judgeStrategy.doJudge(judgeContext);
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        // 更新判题结果到数据库
        updateQuestionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        updateQuestionSubmit.setStatus(QuestionSubmitStatusEnum.SUCCEED.getValue());
        update = questionSubmitService.updateById(updateQuestionSubmit);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "题目提交更新错误");
        // 返回结果
        return questionSubmitService.getById(questionSubmitId);
    }
}
